<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/04/03
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\order;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use ImiApp\ApiServer\Api\Controller\Tpmecms;

use ImiApp\ApiServer\Api\Model\Goods;
use ImiApp\ApiServer\Api\Model\GoodsCate;

/**
 * 订单
 * 
 */
class OrderBean extends Tpmecms
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 获取商品价格id
     *
     * @param int $goods_id 商品id
     * @param int $goods_sku_price_id 规格id
     * @return float
     */
    protected function GetGoodsPrice($goods_id, $goods_sku_price_id = null)
    {
        $goods = Db::name('goods')
            ->where('id', '=', $goods_id)
            // ->cache($this->db_cache_set)
            ->select()->get();
        if ($goods['is_sku']) {
            //多规格
            $price = Db::name('goodssku_price')
                ->where('id', '=', $goods_sku_price_id)
                // ->cache($this->db_cache_set)
                ->value('price');
        } else {
            $price = $goods['price'];
        }
        if ($price < 0.01) {
            return $this->error('该商品价格低于0.01');
        }
        return $price;
    }

    /**
     * 获取商品运费
     *
     * @param int|string $goods_id
     * @return float
     */
    protected function GetGoodsDispatchAmount($goods_id)
    {
        return 0;
        $goods = Db::name('goods')
            ->where('id', '=', $goods_id)
            // ->cache($this->db_cache_set)
            ->select()->get();
    }




    /**
     *获取商品规格价格
     *
     * @param int $goods_sku_price_id 规格id
     * @return void
     */
    protected function GetGoodsskuPriceData($goods_sku_price_id)
    {

        $goodssku_price = Db::name('goodssku_price')
            ->where('id', '=', $goods_sku_price_id)
            // ->cache($this->db_cache_set)
            ->find();
        if (!$goodssku_price) {
            return $this->error('暂无该规格', $goods_sku_price_id);
        }
        // $goods = Goods::find(['id'=>$goodssku_price['goods_id']]);
        // if(!$goods){
        //     return $this->error('该商品不存在');
        // }
        // if($goods['status']=='down'){
        //     return $this->error('该商品已下架');
        // }
        // if($goodssku_price['status']=='down'){
        //     return $this->error('该规格已下架',$goods_sku_price_id);
        // }
        // if($goodssku_price['stock']<$num){
        //     return $this->error('库存不足',$goodssku_price);
        // }
        return $goodssku_price;
    }


    /**
     *获取商品是否能创建订单
     *
     * @param int|null $goods_sku_price_id 规格id
     * @param int $num 数量
     * @return void
     */
    protected function GetGoodsIsCreateOrder($goods_sku_price_id, $num)
    {

        $goodssku_price = Db::name('goodssku_price')
            ->where('id', '=', $goods_sku_price_id)
            // ->cache($this->db_cache_set)
            ->find();
        if (!$goodssku_price) {
            return $this->error('暂无该规格', $goods_sku_price_id, CODE_暂无该规格);
        }
        $goods = $this->GetGoodsDataById($goodssku_price['goods_id']); //Goods::find(['id'=>$goodssku_price['goods_id']]);
        if (!$goods) {
            return $this->error('该商品不存在', $goodssku_price['goods_id'], CODE_该商品不存在);
        }
        if ($goods['status'] == 'down') {
            return $this->error('该商品已下架', null, CODE_该商品已下架);
        }
        if ($goodssku_price['status'] == 'down') {
            return $this->error('该规格已下架', $goods_sku_price_id, CODE_该规格已下架);
        }
        if ($goodssku_price['stock'] < $num) {
            return $this->error($goods['title'].'⭐️库存不足', $goodssku_price, CODE_库存不足);
        }
        return $goodssku_price;
    }


    /**
     * 取消总订单
     *
     * @param int $order_id
     * @return void
     */
    protected function CancelTotalOrder(?int $order_id)
    {
        $main_order['id'] = $order_id;
        $order_data = Db::name('order_total')->whereEx($main_order)->find();
        ////支付状态:1=待支付,2=已支付,3=已退款,4=已超时
        if ($order_data['pay_status'] == '1') {
            //修改主状态
            $update_main['pay_status'] = '4';
            Db::name('order_total')->whereEx($main_order)->update($update_main);
            //循环取消子订单
            $order_list = Db::name('order')->whereIn('id', explode(',', $order_data['order_ids']))->select()->getArray();
            foreach ($order_list as $key => $val) {
                //
                //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成 
                Db::name('order')->where('id', '=', $val['id'])->update(['status' => '-1', 'updatetime' => time()]);

                //加入库存
                $this->IncOrderGoodsStock($val['id'], '取消总订单');
            }
        } else {
            return $this->error('只有待支付的订单才可以取消');
        }
    }


    /**
     * 超时取消总订单
     *
     * @param int $order_id
     * @return void
     */
    protected function TimeOutCancelTotalOrder($order_id)
    {
        $main_order['id'] = $order_id;
        $order_data = Db::name('order_total')->whereEx($main_order)->find();
        if ($order_data) {
            ////支付状态:1=待支付,2=已支付,3=已退款,4=已超时

            if ($order_data['pay_status'] == '1') {
                //修改主状态
                $update_main['pay_status'] = '4';
                Db::name('order_total')->whereEx($main_order)->update($update_main);
                //循环取消子订单
                $order_list = Db::name('order')->whereIn('id', explode(',', $order_data['order_ids']))->select()->getArray();
                foreach ($order_list as $key => $val) {
                    //
                    //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成 
                    Db::name('order')->where('id', '=', $val['id'])->update(['status' => '-2', 'updatetime' => time()]);

                    //加入库存
                    $this->IncOrderGoodsStock($val['id'], '超时取消总订单');
                }
            } else {
                \Imi\Log\Log::error('主订单非待支付状态' . $order_id);
            }
        } else {
            \Imi\Log\Log::error('主订单超时,未找到' . $order_id);
        }
    }


    /**
     * 增加订单商品库存
     *
     * @param int $order_id 订单id
     * @param string $ps 备注
     * @return void 
     */
    protected function IncOrderGoodsStock($order_id, $ps = null)
    {
        $list = Db::name('order_item')->where('order_id', '=', $order_id)->select()->getArray();
        foreach ($list as $key => $val) {
            $this->IncGoodsStock($val['goods_sku_price_id'], $val['goods_num'], $ps, $order_id);
        }
    }


    //创建订单完成后 定时多久未支付就恢复库存

    //如果支付了取消定时


    /**
     * 订单超时
     *
     * @param int $order_id
     * @return void
     */
    protected function OrderTimeout($order_id)
    {
        //查询订单是否超时

        $this->TimeOutCancelTotalOrder($order_id);
        //超时 查询 子订单 退回库存

    }







    /**
     * 获取地址信息🌍
     *
     * @param int $id 地址id
     * @return void
     */
    protected function GetAddrData($id)
    {
        $addr = Db::name('addr')->where('id', '=', $id)->select()->get();
        if (!$addr) {
            return $this->error('该地址不存在', $id, CODE_该地址不存在);
        }
        return $addr;
        // $addr['']
    }

    /**
     * 获取支付金额详情
     *
     * @param float $pay 支付金额
     * @param float $shell 贝壳
     * @param float $score 积分
     * @param int $coupons_id 优惠券
     * @return array
     */
    public function get_pay_money_info($pay = 0, $shell = 0, $score = 0, $coupons_id = null)
    {
        //需要支付的金额 如果有优惠券 先减去优惠券
        if ($coupons_id) {

            $需要支付的金额 = $pay - 20;
        } else {
            $需要支付的金额 = $pay;
        }
        $最多可用积分 = $this->UserUsableScore($需要支付的金额, $this->auth->user()->set_id, $this->auth->user()->id);

        $积分服务费 = $this->UserPayScoreServerFee($最多可用积分, $this->auth->user()->set_id, $this->auth->user()->id);

        //  贝壳当现金用
        $实际需要支付金额 = $需要支付的金额 - $最多可用积分 - $shell + $积分服务费;

        return ['max_score' => $最多可用积分, 'money' => $实际需要支付金额, 'score_server_fee' => $积分服务费];
        // $最多可用积分 = $需要支付的金额 * $最多可用积分比率;

    }
}
